<template>
	<div></div>
</template>
<script>
import {
	mapState
} from 'vuex';
export default {
	props: {
		userId: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			lockReconnect: false, //是否真正建立连接
			timeout: 5 * 1000, // 5秒一次心跳

			timer: null, // 心跳倒计时
			serverTimer: null, //心跳倒计时
			timeoutnum: null, //断开 重连倒计时
		};
	},
	computed: {
		...mapState(['websock', 'user'])
	},
	created() {
		this.initWebSocket();
	},
	// 销毁定时器
	beforeDestroy() {
		this.websock && this.websock.close(); //离开路由之后断开websocket连接
		this.timer && clearTimeout(this.timer)
		this.serverTimer && clearTimeout(this.serverTimer)
		this.timeoutnum && clearTimeout(this.timeoutnum)
		this.timer = null
		this.serverTimer = null
		this.timeoutnum = null
	},
	methods: {
		initWebSocket() {
			//初始化weosocket
			const wsuri = 'wss://5gmeetingmid.pathologyunion.com:3985/ws/'
			// 'ws://192.168.5.229:3985/ws/'
			const websock = new WebSocket(wsuri);

			// 客户端接收服务端数据时触发
			websock.onmessage = this.websocketonmessage;
			// 连接建立时触发
			websock.onopen = this.websocketonopen;
			// 通信发生错误时触发
			websock.onerror = this.websocketonerror;
			// 连接关闭时触发
			websock.onclose = this.websocketclose;

			this.$store.commit('SET_WEBSOCK', websock)
		},
		// 连接建立时触发
		websocketonopen() {

			//连接建立之后执行send方法发送数据
			console.log('用户上线');
			const msg = {
				event: 'userOnline',
				userId: this.userId
			}
			this.websocketsend(JSON.stringify(msg))

		},
		// 通信发生错误时触发
		websocketonerror() {
			console.log("出现错误");
			this.reconnect();
		},
		// 客户端接收服务端数据时触发
		websocketonmessage(e) {
			const data = JSON.parse(e.data)
			const {
				data: info
			} = data
			if (data.event == 'userNotification') {
				console.log('快速入会通知', info);
				if (data.userId == this.userId || this.isDevice) return
				this.$confirm(`用户${info.userName}邀请你加入会议${info.meetingRoomName}`, '加入会议提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消'
				}).then(() => {
					this.$router.push({
						path: "/room",
						query: {
							code: info.code,
							spaceType: 0
						}
					})
				}).catch(() => { });
			}
			//收到服务器信息，心跳重置
			this.reset();
		},
		websocketsend(Data) {
			//数据发送
			this.websock.send(Data);
		},
		// 连接关闭时触发
		websocketclose(e) {
			//关闭
			console.log("断开连接", e);
			//重连
			this.reconnect();
		},
		reconnect() {
			//重新连接
			var that = this;
			if (that.lockReconnect || !that.websock) {
				return;
			}
			that.lockReconnect = true;
			//没连接上会一直重连，设置延迟避免请求过多
			that.timeoutnum && clearTimeout(that.timeoutnum);
			that.timeoutnum = setTimeout(function () {
				//新连接
				that.initWebSocket();
				that.lockReconnect = false;
			}, 5000);
		},
		reset() {
			//重置心跳
			var that = this;
			//清除时间
			clearTimeout(that.timer);
			clearTimeout(that.serverTimer);
			//重启心跳
			that.start();
		},
		start() {
			console.log("心跳：" + new Date().getTime());

			var self = this;
			self.timer && clearTimeout(self.timer)
			self.serverTimer && clearTimeout(self.serverTimer);

			self.timer = setTimeout(function () {
				//这里发送一个心跳，后端收到后，返回一个心跳消息，
				if (self.websock.readyState == 1) {
					//如果连接正常
					const msg = {
						event: 'heart',
						userId: self.userId
					}
					self.websocketsend(JSON.stringify(msg))

				} else {
					//否则重连
					self.reconnect();
				}

				self.serverTimer = setTimeout(function () {
					//超时关闭
					self.websock.close();

				}, self.timeout);

			}, self.timeout);
		},
	}
};
</script>